package org.spotem.service;

import org.spotem.common.BaseException;
import org.spotem.dao.UserRepo;
import org.spotem.model.UserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class UserService extends BaseService {

    @Autowired
    private UserRepo userRepo;

    @Transactional(readOnly = false, rollbackFor = BaseException.class)
    public UserImpl findUser(String login) {
        List<UserImpl> users = userRepo.findByLogin(login);
        if(users == null || users.isEmpty()) {
            UserImpl user = new UserImpl();
            user.setLogin(login);
            user.setName(login);
            user.setPassword("");
            userRepo.save(user);
            return user;
        } else {
            return users.iterator().next();
        }
    }
}
